// 参考: https://www.jianshu.com/p/b895c22c85af


<template>
    <div class="console" id="terminal"></div>
</template>
<script>
import 'xterm/css/xterm.css'
import { Terminal } from 'xterm'
import {FitAddon} from 'xterm-addon-fit'
import { AttachAddon } from 'xterm-addon-attach'

export default {
  name: 'sshTerminal',
  props: {
    terminal: {
      type: Object,
    //   default: {}
    }
  },
  data () {
    return {
      term: null,
      ws: null
    }
  },
  mounted () {
    this.initSocket()
  },
  methods: {
    initTerminal() {
      console.log('pid : ' + this.terminal.pid + ' is on ready')
      console.log(this.terminal.websocket_url)
      let terminalContainer = document.getElementById('terminal')
      const term = new Terminal({
          fontSize: 18,
          cursorBlink: true
      })
      const attachAddon = new AttachAddon(this.ws);
      const  fitAddon = new FitAddon();
      term.loadAddon(attachAddon);
      term.loadAddon(fitAddon);
      
      term.open(terminalContainer)
      term.focus();
      this.term = term
      console.log('mounted is going on')
    },
    initSocket() {
      let url = this.terminal.websocket_url
      this.ws = new WebSocket(url)
      this.socketOnClose()
      this.socketOnOpen()
      this.socketOnError()
    },
    socketOnOpen() {
      this.ws.onopen = () => {
        // 链接成功后
        this.initTerminal()
      }
    },
    socketOnClose() {
      this.ws.onclose = () => {
        this.ws.close()
        console.log(this.terminal.pid  + ' close socket')
      }
    },
    socketOnError() {
      this.ws.onerror = () => {
        console.log(this.terminal.pid + ' socket 链接失败')
      }
    }

  },
  beforeDestroy () {
    console.log("destroy")
    this.ws.close()
    this.term.dispose()
  }
}
</script>